#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mywidget.h"
#include "fileworker.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 设置窗口标题
    setWindowTitle(QString("界面程序-谢育豪-") + QDate::currentDate().toString("yyyy-MM-dd"));

    // 创建菜单栏
    QMenuBar *mb = menuBar();
    QMenu *fileMenu = mb->addMenu("文件");
    QMenu *viewMenu = mb->addMenu("视图");
    QMenu *setMenu = mb->addMenu("设置");
    QMenu *helpMenu = mb->addMenu("帮助");
    viewMenu->addAction("打开新页面", this, &MainWindow::openNewPage);

    // 创建工具栏
    QToolBar *tb = addToolBar("工具栏");
    for(int i=1; i<=5; i++)
    {
        QAction *act = tb->addAction(QIcon(QString(":/Icon/%1.png").arg(i)), QString("动作%1").arg(i));
        connect(act, &QAction::triggered, [i](){ qDebug() << "执行动作" << i; });
    }

    //创建状态栏
    QStatusBar *sb = statusBar();
    QLabel *left = new QLabel("左侧状态");
    QLabel *right1 = new QLabel("右侧状态1");
    QLabel *right2 = new QLabel("右侧状态2");

    sb->addWidget(left);
    sb->addPermanentWidget(right1);
    sb->addPermanentWidget(right2);

    // 主界面布局
    QWidget *central = new QWidget;
    setCentralWidget(central);
    QVBoxLayout *mainLayout = new QVBoxLayout(central);

    //创建表格和倒序按钮
    setupTable();
    QPushButton *reverseBtn = new QPushButton("倒序");
    connect(reverseBtn, &QPushButton::clicked, this, &MainWindow::reverseTable);

    QHBoxLayout *tableLayout = new QHBoxLayout;
    tableLayout->addWidget(tableView);
    tableLayout->addWidget(reverseBtn);
    mainLayout->addLayout(tableLayout);

    //创建树形图和按钮
    setupTreeView();
    QPushButton *processBtn = new QPushButton("处理数据");
    QPushButton *filterBtn = new QPushButton("过滤行");
    connect(processBtn, &QPushButton::clicked, this, &MainWindow::processTreeData);
    connect(filterBtn, &QPushButton::clicked, this, &MainWindow::filterTreeRows);

    QHBoxLayout *treeLayout = new QHBoxLayout;
    treeLayout->addWidget(treeView);
    QVBoxLayout *btnLayout = new QVBoxLayout;
    btnLayout->addWidget(processBtn);
    btnLayout->addWidget(filterBtn);
    treeLayout->addLayout(btnLayout);
    mainLayout->addLayout(treeLayout);

    //创建绘画控件
    MyWidget *customWidget = new MyWidget;
    customWidget->setMinimumSize(200, 150);
    mainLayout->addWidget(customWidget);

    //创建通信按钮和文本显示区域
    m_textDisplay = new QPlainTextEdit;
    m_textDisplay->setReadOnly(true);
    m_controlButton = new QPushButton("开始通信");
    connect(m_controlButton, &QPushButton::clicked, this, &MainWindow::toggleCommunication);
    mainLayout->addWidget(m_textDisplay);
    mainLayout->addWidget(m_controlButton);
    setupServer();  //设置服务器
    setupClient();  //设置客户端

    //创建写入文件按钮
    m_button = new QPushButton("开始写入文件", this);
    connect(m_button, &QPushButton::clicked, this, &MainWindow::selectAndWrite);
    mainLayout->addWidget(m_button);

    //创建操作数据库的三个按钮
    m_btnCreate = new QPushButton("1. 创建数据表并插入数据");
    m_btnSort = new QPushButton("2. 按随机数2降序排序");
    m_btnProcess = new QPushButton("3. 处理奇数行并删除偶数行");
    mainLayout->addWidget(m_btnCreate);
    mainLayout->addWidget(m_btnSort);
    mainLayout->addWidget(m_btnProcess);
    connect(m_btnCreate, &QPushButton::clicked, this, &MainWindow::createTable);
    connect(m_btnSort, &QPushButton::clicked, this, &MainWindow::sortData);
    connect(m_btnProcess, &QPushButton::clicked, this, &MainWindow::processOddRows);
    initDB(); // 初始化

}

MainWindow::~MainWindow()
{
    if(m_serverSocket) m_serverSocket->close();
    if(m_clientSocket) m_clientSocket->close();
    m_tcpServer->close();
    if(m_db.isOpen())
    {
        m_db.close();
    }
    delete ui;
}

//打开新页面
void MainWindow::openNewPage()
{
    MainWindow *newWin = new MainWindow;
    newWin->show();
}

//创建表格
void MainWindow::setupTable()
{
    tableView = new QTableView;
    tableModel = new QStandardItemModel(8, 5, this);
    for(int i=0; i<5; i++)
        tableModel->setHeaderData(i, Qt::Horizontal, QString("列%1").arg(i+1));

    // 填充测试数据
    for(int row=0; row<8; row++)
    {
        for(int col=0; col<5; col++)
        {
            int num = QRandomGenerator::global()->bounded(1, 100);
            QStandardItem *item = new QStandardItem(QString::number(num));
            tableModel->setItem(row, col, item);
        }
    }
    tableView->setModel(tableModel);
}

//创建树形图
void MainWindow::setupTreeView()
{
    treeView = new QTreeView;
    treeModel = new QStandardItemModel(8, 5, this);
    for(int i=0; i<5; i++)
        treeModel->setHeaderData(i, Qt::Horizontal, QString("树列%1").arg(i+1));

    // 填充随机数据
    for(int row=0; row<8; row++)
    {
        for(int col=0; col<5; col++)
        {
            int num = QRandomGenerator::global()->bounded(50);
            QStandardItem *item = new QStandardItem(QString::number(num));
            treeModel->setItem(row, col, item);

            // 添加子项用于展开
            for(int i=0; i<3; i++)
            {
                QStandardItem *child = new QStandardItem(QString("子项%1").arg(i));
                item->appendRow(child);
            }
        }
    }
    treeView->setModel(treeModel);
}

//设置服务器
void MainWindow::setupServer()
{
    m_tcpServer = new QTcpServer(this);
    if(!m_tcpServer->listen(QHostAddress::LocalHost, PORT))
    {
        QMessageBox::critical(this, "错误",
            QString("无法启动服务器: %1").arg(m_tcpServer->errorString()));
    }
    connect(m_tcpServer, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection);
}

//设置客户端
void MainWindow::setupClient()
{
    m_clientSocket = new QTcpSocket(this);
    m_sendTimer = new QTimer(this);
    m_sendTimer->setInterval(500);

    connect(m_clientSocket, &QTcpSocket::connected, this, &MainWindow::handleClientConnected);
    connect(m_clientSocket, &QTcpSocket::readyRead, this, &MainWindow::handleClientReadyRead);
    connect(m_clientSocket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
            this, &MainWindow::handleSocketError);
    connect(m_sendTimer, &QTimer::timeout, this, &MainWindow::sendClientData);
}

//数据库初始化
void MainWindow::initDB()
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("test.db");

    if(!m_db.open())
    {
        showError(m_db.lastError());
    }
}

void MainWindow::showError(const QSqlError &err)
{
    m_textDisplay->appendPlainText("错误: " + err.text());
}

//倒序
void MainWindow::reverseTable()
{
    // 按列进行倒序处理
    for(int col = 0; col < tableModel->columnCount(); ++col)
    {
        // 收集本列所有数据
        QVector<QString> columnData;
        for(int row = 0; row < tableModel->rowCount(); ++row)
        {
            if(QStandardItem *item = tableModel->item(row, col))
            {
                columnData.append(item->text());
            }
        }

        // 反转数据顺序
        std::reverse(columnData.begin(), columnData.end());

        // 写回数据
        for(int row = 0; row < tableModel->rowCount(); ++row)
        {
            if(QStandardItem *item = tableModel->item(row, col))
            {
                item->setText(columnData[row]);
            }
        }
    }
}

//把<=25的数据变成0
void MainWindow::processTreeData()
{
    for(int row=0; row<treeModel->rowCount(); row++)
    {
        for(int col=0; col<treeModel->columnCount(); col++)
        {
            QStandardItem *item = treeModel->item(row, col);
            if(item->text().toInt() <= 25)
                item->setText("0");
        }
    }
}

//过滤出单数行
void MainWindow::filterTreeRows()
{
    for(int row = treeModel->rowCount()-1; row >=0; row--)
    {
        if(row % 2 == 0)
            treeModel->removeRow(row);
    }
}

//点击通信
void MainWindow::toggleCommunication()
{
    m_textDisplay->clear();
    if(m_sendTimer->isActive())
    {
        // 停止通信
        m_sendTimer->stop();
        m_clientSocket->disconnectFromHost();
        m_controlButton->setText("开始通信");
        m_controlButton->setEnabled(true);
        m_textDisplay->appendPlainText("通信已停止");
    } else
    {
        // 开始连接
        m_clientSocket->connectToHost(QHostAddress::LocalHost, PORT);
        m_controlButton->setEnabled(false);
        m_textDisplay->appendPlainText("正在连接本地服务器...");
        // 超时检测
        QTimer::singleShot(3000, this, [this](){
            if(m_clientSocket->state() != QAbstractSocket::ConnectedState)
            {
                m_controlButton->setEnabled(true);
                m_textDisplay->appendPlainText("连接超时");
            }
        });
    }
}

//处理新连接
void MainWindow::handleNewConnection()
{
    m_serverSocket = m_tcpServer->nextPendingConnection();
    connect(m_serverSocket, &QTcpSocket::readyRead, this, &MainWindow::handleServerReadyRead);
    connect(m_serverSocket, &QTcpSocket::disconnected, this, [this](){
        m_textDisplay->appendPlainText("客户端断开连接");
    });

    m_textDisplay->appendPlainText("客户端已连接");
    m_serverSocket->write("服务端就绪\n");
}

//服务器读取
void MainWindow::handleServerReadyRead()
{
    QByteArray data = m_serverSocket->readAll();
    QString message = QString("服务器接收: %1 [%2]")
                        .arg(QString::fromUtf8(data))
                        .arg(QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
    m_textDisplay->appendPlainText(message);
}

void MainWindow::handleClientConnected()
{
    m_sendTimer->start();  // 启动定时器
    m_controlButton->setText("停止通信");
    m_controlButton->setEnabled(true);
    m_textDisplay->appendPlainText("已连接到服务器");
}

//客户端读取
void MainWindow::handleClientReadyRead()
{
    QByteArray data = m_clientSocket->readAll();
    QString message = QString("客户端接收: %1 [%2]")
                        .arg(QString::fromUtf8(data))
                        .arg(QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));
    m_textDisplay->appendPlainText(message);
}

//处理套接字错误
void MainWindow::handleSocketError(QAbstractSocket::SocketError error)
{
    Q_UNUSED(error);
    m_sendTimer->stop();
    m_controlButton->setText("开始通信");
    m_controlButton->setEnabled(true);
    m_textDisplay->appendPlainText("错误: " + m_clientSocket->errorString());
}

//发送客户端数据
void MainWindow::sendClientData()
{
    if(m_clientSocket->state() == QAbstractSocket::ConnectedState)
    {
        QString message = QString("客户端数据%1 [%2]")
                            .arg(m_sendCounter++)
                            .arg(QDateTime::currentDateTime().toString("hh:mm:ss.zzz"));

        m_clientSocket->write(message.toUtf8());
        m_clientSocket->flush();  // 强制立即发送

        m_textDisplay->appendPlainText("发送: " + message);
    } else
    {
        m_textDisplay->appendPlainText("连接已断开，停止发送");
        m_sendTimer->stop();
        m_controlButton->setText("开始通信");
    }
}

//选择和写入
void MainWindow::selectAndWrite()
{
    QString dir = QFileDialog::getExistingDirectory(this, "选择保存目录");
    if(dir.isEmpty()) return;

    QString filePath = dir + "/hello.txt";

    // 创建线程和worker对象
    QThread *thread = new QThread;
    FileWorker *worker = new FileWorker(filePath);

    worker->moveToThread(thread);

    // 连接信号槽
    connect(thread, &QThread::started, worker, &FileWorker::startWork);
    connect(worker, &FileWorker::progress, this, &MainWindow::handleProgress);
    connect(worker, &FileWorker::finished, this, [this, thread](){
        thread->quit();
        QMessageBox::information(this, "完成", "文件写入完成");
    });
    connect(worker, &FileWorker::finished, this, &MainWindow::handleFinished);
    connect(worker, &FileWorker::errorOccurred, this, [this](const QString &msg){
        QMessageBox::critical(this, "错误", msg);
    });

    // 自动清理资源
    connect(thread, &QThread::finished, worker, &QObject::deleteLater);
    connect(thread, &QThread::finished, thread, &QObject::deleteLater);

    thread->start();
}

//写入进度
void MainWindow::handleProgress(int value)
{
    m_button->setText(QString("正在写入 (%1/100)").arg(value));
}

//写完
void MainWindow::handleFinished()
{
    m_button->setText("开始写入文件");
}

//创建数据表并插入数据
void MainWindow::createTable()
{
    QSqlQuery query;

    // 删除旧表
    if(!query.exec("DROP TABLE IF EXISTS 数据库表1"))
    {
        showError(query.lastError());
        return;
    }

    // 创建新表
    QString createSQL =
        "CREATE TABLE 数据库表1 ("
        "序号 INTEGER PRIMARY KEY, "
        "随机数1 INTEGER, "
        "随机数2 INTEGER, "
        "随机数3 INTEGER)";

    if(!query.exec(createSQL))
    {
        showError(query.lastError());
        return;
    }

    // 批量插入数据
    m_db.transaction();
    query.prepare("INSERT INTO 数据库表1 VALUES (?, ?, ?, ?)");

    for(int i=0; i<1000; ++i)
    {
        query.addBindValue(i);
        query.addBindValue(QRandomGenerator::global()->bounded(3000));
        query.addBindValue(QRandomGenerator::global()->bounded(3000));
        query.addBindValue(QRandomGenerator::global()->bounded(3000));

        if(!query.exec())
        {
            showError(query.lastError());
            m_db.rollback();
            return;
        }
    }

    m_db.commit();
    m_textDisplay->clear();
    m_textDisplay->appendPlainText(QString("数据创建完成 [%1]")
                                   .arg(QDateTime::currentDateTime().toString()));
}

//按随机数2降序排序
void MainWindow::sortData()
{
    QSqlQuery query;
    QString sql =
        "SELECT * FROM 数据库表1 "
        "ORDER BY 随机数2 DESC";

    if(!query.exec(sql))
    {
        showError(query.lastError());
        return;
    }

    // 显示前10条结果示例
    m_textDisplay->clear();
    m_textDisplay->appendPlainText("\n排序结果（示例）：");
    int count = 0;
    while(query.next() && count++ < 10)
    {
        m_textDisplay->appendPlainText(
            QString("%1 | %2 | %3 | %4")
                .arg(query.value(0).toInt(), 4)
                .arg(query.value(1).toInt(), 4)
                .arg(query.value(2).toInt(), 4)
                .arg(query.value(3).toInt(), 4));
    }
}

//处理奇数行并删除偶数行
void MainWindow::processOddRows()
{
    // 打印奇数行
    QSqlQuery query;
    QString printSQL =
        "SELECT * FROM 数据库表1 "
        "WHERE 随机数3 % 2 = 1";

    if(!query.exec(printSQL))
    {
        showError(query.lastError());
        return;
    }

    m_textDisplay->clear();
    m_textDisplay->appendPlainText("\n奇数行数据：");
    while(query.next())
    {
        m_textDisplay->appendPlainText(
            QString("%1 | %2 | %3 | %4")
                .arg(query.value(0).toInt(), 4)
                .arg(query.value(1).toInt(), 4)
                .arg(query.value(2).toInt(), 4)
                .arg(query.value(3).toInt(), 4));
    }

    // 删除偶数行
    QSqlQuery delQuery;
    if(!delQuery.exec("DELETE FROM 数据库表1 WHERE 随机数3 % 2 = 0"))
    {
        showError(delQuery.lastError());
        return;
    }

    m_textDisplay->appendPlainText(QString("\n删除完成，剩余%1条数据 [%2]")
                               .arg(delQuery.numRowsAffected())
                               .arg(QDateTime::currentDateTime().toString()));
}
